package com.example.security.service;

import com.example.security.entity.SysUser;
import com.example.security.mapper.UserMapper;

import com.example.security.vo.LoginRequest;
import com.example.security.vo.LoginResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
import java.util.Set;

@Service
@RequiredArgsConstructor
@Slf4j
public class AuthService {
    
    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    private final JwtService jwtService;
    private final RedisTemplate<String, Object> redisTemplate;
    private final PermissionService permissionService;
    private final UserService userService;
    @Autowired
    private UserDetailsService userDetailsService ;

    public LoginResponse login(LoginRequest request) {
        // 查找用户
        SysUser user = userMapper.findByUserId(request.getUserId())
            .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
            
        // 验证密码
        if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            throw new BadCredentialsException("密码错误");
        }
        
        // 生成token
        UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUsername());
        String token = jwtService.generateToken(userDetails);
        
        // 存储token
        redisTemplate.opsForValue().set(
            "token:" + user.getUsername(),
            token,
            7200,
            TimeUnit.SECONDS
        );
        
        // 获取用户权限
        Set<String> permissions = permissionService.getUserPermissions(user.getId());
        
        // 构建响应
        return LoginResponse.builder()
            .token(token)
            .user(user)
            .permissions(permissions)
            .build();
    }

    public void logout(String token) {
        String username = jwtService.extractUsername(token);
        redisTemplate.delete("token:" + username);
        redisTemplate.delete("auth:" + token);
        redisTemplate.delete("user:" + username);
    }
} 